package jsyf.oa.service.wreport;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.email.EmailDao;
import jsyf.oa.dao.email.EmailReceiverDao;
import jsyf.oa.dao.email.WreportReceiverCopiersDao;
import jsyf.oa.dao.system.RegionDao;
import jsyf.oa.dao.system.RoleDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.thurTrack.ThurTrackDao;
import jsyf.oa.dao.weekplan.TomorrowVisitDao;
import jsyf.oa.dao.wreport.CostAuditDao;
import jsyf.oa.dao.wreport.CostDetailDao;
import jsyf.oa.dao.wreport.WReportBranchDao;
import jsyf.oa.dao.wreport.WReportCostDao;
import jsyf.oa.dao.wreport.WReportCusAndVisitDao;
import jsyf.oa.dao.wreport.WReportCusVisitDao;
import jsyf.oa.dao.wreport.WReportCustomerDao;
import jsyf.oa.dao.wreport.WReportDetailDao;
import jsyf.oa.dao.wreport.WReportExpensesDao;
import jsyf.oa.dao.wreport.WReportGatherDao;
import jsyf.oa.dao.wreport.WReportMainDao;
import jsyf.oa.dao.wreport.WReportUnfinishDao;
import jsyf.oa.dao.wreport.WReportUnfinishMainDao;
import jsyf.oa.dao.wreport.WReportVieDao;
import jsyf.oa.entity.email.EmailEntity;
import jsyf.oa.entity.email.EmailMainEntity;
import jsyf.oa.entity.system.UserEntity;
import jsyf.oa.entity.thurTrack.ThurTrackEntity;
import jsyf.oa.entity.weekplan.TomorrowVisitPlanEntity;
import jsyf.oa.entity.wreport.WReportBranchEntity;
import jsyf.oa.entity.wreport.WReportCostEntity;
import jsyf.oa.entity.wreport.WReportCusAndVistEntity;
import jsyf.oa.entity.wreport.WReportCusVisitEntity;
import jsyf.oa.entity.wreport.WReportCustomerEntity;
import jsyf.oa.entity.wreport.WReportDetailEntity;
import jsyf.oa.entity.wreport.WReportEntity;
import jsyf.oa.entity.wreport.WReportGatherEntity;
import jsyf.oa.entity.wreport.WReportMainEntity;
import jsyf.oa.entity.wreport.WReportUnfinishEntity;
import jsyf.oa.entity.wreport.WReportUnfinishMainEntity;
import jsyf.oa.entity.wreport.WReportVieEntity;
import jsyf.oa.facade.wreport.WReportFacade;
import jsyf.oa.service.email.EmailService;


/**
 * Created by Administrator on 2017/11/22 0022.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class WReportService implements WReportFacade {

    @Autowired
    private WReportMainDao wReportMainDao;
    @Autowired
    private WReportDetailDao wReportDetailDao;
    @Autowired
    private WreportReceiverCopiersDao wreportReceiverCopiersDao;
    @Autowired
    private WReportUnfinishDao wReportUnfinishDao;

    @Autowired
    private WReportCustomerDao wReportCustomerDao;

    @Autowired
    private WReportCusVisitDao wRportCusVisitDao;

    @Autowired
    private WReportCusAndVisitDao wReportCusAndVisitDao;

    @Autowired
    private WReportCostDao wReportCostDao;

    @Autowired
    private WReportBranchDao wReportBranchDao;

    @Autowired
    private WReportGatherDao wReportGatherDao;

    @Autowired
    private WReportVieDao wReportVieDao;

    @Autowired
    private EmailDao emailDao;

    @Autowired
    private WReportExpensesDao wReportExpensesDao;

    @Autowired
    private WReportUnfinishMainDao wReportUnfinishMainDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private EmailReceiverDao emailReceiverDao;
    @Autowired
    private CostDetailDao costDetailDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private RegionDao regionDao;

    @Autowired
    private EmailService emailService;

    @Autowired
    private TomorrowVisitDao tomorrowVisitDao;

    @Autowired
    private CostAuditDao costAuditDao;
    @Autowired
    private ThurTrackDao thurTrackDao;

    @Override
    public String save(String jsonData) {
        WReportEntity wReportEntity = JSON.toJavaObject(JSON.parseObject(jsonData), WReportEntity.class);
        //根据userId，reportDate删除工作报告
        wReportMainDao.removeByUserIdAndReportDate(wReportEntity.getMain().getUserId(), wReportEntity.getMain().getReportDate());
        wReportCostDao.remove(wReportEntity.getMain().getReportDate(), wReportEntity.getMain().getUserId());

        /*if (wReportEntity.getMain().getFlage().equals("0") && !wReportEntity.getMain().getId().equals("0") && !StringUtils.isEmpty(wReportEntity.getMain().getId())) {
            emailDao.removeByTypeAndDataId("1", wReportEntity.getMain().getId());
        }*/
        emailDao.removeByCondition(" AND CREATE_USER_ID = ? AND REPORT_DATE = ? ", new String[]{wReportEntity.getMain().getUserId(), wReportEntity.getMain().getReportDate()});
        //保存工作报告主题信息
        wReportMainDao.add(wReportEntity.getMain());
        String wId = wReportEntity.getMain().getId();
        //心得体会
        if (wReportEntity.getExperience() != null && !StringUtils.isEmpty(wReportEntity.getExperience().getContent())) {
            wReportEntity.getExperience().setwId(wId);
            wReportDetailDao.add(wReportEntity.getExperience());
        }

        //次日上午安排
        if (wReportEntity.getTomorrowAMPlan() != null && !StringUtils.isEmpty(wReportEntity.getTomorrowAMPlan().getContent())) {
            wReportEntity.getTomorrowAMPlan().setwId(wId);
            wReportDetailDao.add(wReportEntity.getTomorrowAMPlan());
        }
        //次日下午安排
        if (wReportEntity.getTomorrowPMPlan() != null && !StringUtils.isEmpty(wReportEntity.getTomorrowPMPlan().getContent())) {
            wReportEntity.getTomorrowPMPlan().setwId(wId);
            wReportDetailDao.add(wReportEntity.getTomorrowPMPlan());
        }

        //第二天计划
        if (wReportEntity.getTomorrowPlan() != null && !StringUtils.isEmpty(wReportEntity.getTomorrowPlan().getContent())) {
            wReportEntity.getTomorrowPlan().setwId(wId);
            wReportDetailDao.add(wReportEntity.getTomorrowPlan());
        }
        //人员情况
        if (wReportEntity.getPersonSituation() != null && !StringUtils.isEmpty(wReportEntity.getPersonSituation().getContent())) {
            wReportEntity.getPersonSituation().setwId(wId);
            wReportDetailDao.add(wReportEntity.getPersonSituation());
        }
        //当天未处理的三个疑难故障
        if (wReportEntity.getTroubleShooting() != null) {
            for (WReportUnfinishEntity troubleShooting : wReportEntity.getTroubleShooting()) {
                //保存主表信息
                String mainId = troubleShooting.getMainId();
                if (wReportEntity.getMain().getFlage().equals("0")) {
                    //如果是发送报告
                    WReportUnfinishMainEntity unfinishMain = new WReportUnfinishMainEntity();
                    if (StringUtils.isEmpty(mainId) || "0".equals(mainId)) {
                        if (!troubleShooting.getTrackContent().equals("")) {
                            unfinishMain.setTrackContent(troubleShooting.getTrackContent());
                            unfinishMain.setType("1");
                            unfinishMain.setUserId(wReportEntity.getMain().getUserId());
                            unfinishMain.setOverTime("");
                            unfinishMain.setJobState("0");
                            unfinishMain.setJinzhan(troubleShooting.getJinzhan());

                            wReportUnfinishMainDao.add(unfinishMain);
                            mainId = unfinishMain.getId();
                        }
                    } else {
                        unfinishMain = (WReportUnfinishMainEntity) wReportUnfinishMainDao.getIBaseEntityById(mainId);
                        unfinishMain.setTrackContent(troubleShooting.getTrackContent());
                        unfinishMain.setJinzhan(troubleShooting.getJinzhan());
                        wReportUnfinishMainDao.update(unfinishMain);
                    }
                }
                //保存子表信息
                if (!troubleShooting.getTrackContent().equals("")) {
                    troubleShooting.setwId(wId);
                    troubleShooting.setJobState("0");
                    troubleShooting.setOverTime("");
                    troubleShooting.setMainId(mainId);
                    troubleShooting.setUserId(wReportEntity.getMain().getUserId());
                    troubleShooting.setType("1");
                    wReportUnfinishDao.add(troubleShooting);
                }
            }
        }
        //未达到拜访量原因
        if (wReportEntity.getVisitLetterReason() != null && !StringUtils.isEmpty(wReportEntity.getVisitLetterReason().getContent())) {
            wReportEntity.getVisitLetterReason().setwId(wId);
            wReportDetailDao.add(wReportEntity.getVisitLetterReason());
        }
        //当天知道丢单情况
        if (wReportEntity.getTodayKnowVieSituation() != null) {
            wReportEntity.getTodayKnowVieSituation().setwId(wId);
            wReportVieDao.add(wReportEntity.getTodayKnowVieSituation());
        }
        //需要支持的事项
        if (wReportEntity.getForSupportMatters() != null) {
            for (WReportUnfinishEntity forSupport : wReportEntity.getForSupportMatters()) {
                //保存主表信息
                String mainId = forSupport.getMainId();
                if (wReportEntity.getMain().getFlage().equals("0")) {
                    WReportUnfinishMainEntity unfinishMain = new WReportUnfinishMainEntity();
                    if (StringUtils.isEmpty(mainId) || "0".equals(mainId)) {
                        if (!forSupport.getTrackContent().equals("")) {
                            unfinishMain.setTrackContent(forSupport.getTrackContent());
                            unfinishMain.setType("2");
                            unfinishMain.setUserId(wReportEntity.getMain().getUserId());
                            unfinishMain.setOverTime("");
                            unfinishMain.setJobState("0");
                            unfinishMain.setJinzhan(forSupport.getJinzhan());

                            wReportUnfinishMainDao.add(unfinishMain);
                            mainId = unfinishMain.getId();
                        }
                    } else {
                        unfinishMain = (WReportUnfinishMainEntity) wReportUnfinishMainDao.getIBaseEntityById(mainId);
                        unfinishMain.setTrackContent(forSupport.getTrackContent());
                        unfinishMain.setJinzhan(forSupport.getJinzhan());
                        wReportUnfinishMainDao.update(unfinishMain);
                    }
                }
                //保存子表信息
                if (!forSupport.getTrackContent().equals("")) {
                    forSupport.setwId(wId);
                    forSupport.setJobState("0");
                    forSupport.setOverTime("");
                    forSupport.setMainId(mainId);
                    forSupport.setUserId(wReportEntity.getMain().getUserId());
                    forSupport.setType("2");
                    wReportUnfinishDao.add(forSupport);
                }
            }
        }
        //当日工作情况描述
        if (wReportEntity.getWorkOnTodayDescs() != null) {
            for (WReportDetailEntity wReportDetailEntity : wReportEntity.getWorkOnTodayDescs()) {
                wReportDetailEntity.setwId(wId);
                wReportDetailEntity.setContent(wReportDetailEntity.getContent().replace("\t", ""));
                wReportDetailDao.add(wReportDetailEntity);
            }
        }
        //未关闭的事项
        if (wReportEntity.getUnfinishes() != null) {
            for (WReportUnfinishEntity unfinishi : wReportEntity.getUnfinishes()) {
                //保存主表信息
                String mainId = unfinishi.getMainId();
                if (wReportEntity.getMain().getFlage().equals("0")) {
                    WReportUnfinishMainEntity unfinishMain = new WReportUnfinishMainEntity();
                    if (StringUtils.isEmpty(mainId) || "0".equals(mainId)) {
                        if (!unfinishi.getTrackContent().equals("")) {
                            unfinishMain.setTrackContent(unfinishi.getTrackContent());
                            unfinishMain.setType("3");
                            unfinishMain.setUserId(wReportEntity.getMain().getUserId());
                            unfinishMain.setOverTime(unfinishi.getOverTime());
                            unfinishMain.setJobState("0");
                            unfinishMain.setJinzhan(unfinishi.getJinzhan());
                            wReportUnfinishMainDao.add(unfinishMain);
                            mainId = unfinishMain.getId();
                        }

                    } else {
                        unfinishMain = (WReportUnfinishMainEntity) wReportUnfinishMainDao.getIBaseEntityById(mainId);
                        unfinishMain.setTrackContent(unfinishi.getTrackContent());
                        unfinishMain.setJinzhan(unfinishi.getJinzhan());
                        unfinishMain.setOverTime(unfinishi.getOverTime());
                        wReportUnfinishMainDao.update(unfinishMain);
                    }
                }
                //保存子表信息
                if (!unfinishi.getTrackContent().equals("")) {
                    unfinishi.setwId(wId);
                    unfinishi.setJobState("0");
                    unfinishi.setOverTime(unfinishi.getOverTime());
                    unfinishi.setMainId(mainId);
                    unfinishi.setUserId(wReportEntity.getMain().getUserId());
                    unfinishi.setType("3");
                    wReportUnfinishDao.add(unfinishi);
                }
            }
        }
        JSONObject jsonObject = userDao.getViewJSONById(wReportEntity.getMain().getUserId());
        Integer frontFlag = null;
        Integer areaType = null;
        if (jsonObject != null) {
            frontFlag = jsonObject.getInteger("frontFlag");
            areaType = jsonObject.getInteger("areaType");
        }
        if (frontFlag == 1 ) {
                wRportCusVisitDao.removeByCondition(" AND REPORT_DATE = ? AND CREATE_USER_ID = ? ", new String[]{wReportEntity.getMain().getReportDate(), wReportEntity.getMain().getUserId()});
            }


        //当日拜访客户(面访)
//        if (wReportEntity.getTodayCustomerVisit() != null) {
//            for (WReportCusAndVistEntity wReportCusAndVistEntity : wReportEntity.getTodayCustomerVisit()) {
//                if (!StringUtils.isEmpty(wReportCusAndVistEntity.getTel())) {
//                    WReportCustomerEntity wReportCustomerEntity = new WReportCustomerEntity();
//                    WReportCusVisitEntity wReportCusVisitEntity = new WReportCusVisitEntity();
//                    wReportCustomerEntity.setTel(wReportCusAndVistEntity.getTel());
//                    wReportCustomerEntity.setName(wReportCusAndVistEntity.getName());
//                    wReportCustomerEntity.setCompanyName(wReportCusAndVistEntity.getCompanyName());
//                   // wReportCustomerEntity.setBirthday(wReportCusAndVistEntity.getBirthDay());
//                    wReportCustomerEntity.setBuildProvinceName(wReportCusAndVistEntity.getBuildProvinceName());
//                    wReportCustomerEntity.setBuildCityName(wReportCusAndVistEntity.getBuildCityName());
//                    wReportCustomerEntity.setBuildCountyName(wReportCusAndVistEntity.getBuildCountyName());
//                    wReportCustomerEntity.setBuildProvinceId(wReportCusAndVistEntity.getBuildProvinceId());
//                    wReportCustomerEntity.setBuildCityId(wReportCusAndVistEntity.getBuildCityId());
//                    wReportCustomerEntity.setBuildCityId(wReportCusAndVistEntity.getBuildCountyId());
//                    wReportCustomerEntity.setCreateUserId(wReportEntity.getMain().getUserId());
//                    wReportCustomerEntity.setSource(wReportCusAndVistEntity.getSource());
//                    wReportCustomerEntity.setIntentionModel(wReportCusAndVistEntity.getIntentionModel());
//                    wReportCustomerEntity.setBuyType(wReportCusAndVistEntity.getBuyType());
//                    wReportCustomerEntity.setBuyDate(wReportCusAndVistEntity.getBuyDate());
//
//                    wReportCustomerEntity.setOtherCondition(wReportCusAndVistEntity.getOtherCondition());
//                    wReportCustomerEntity.setFundCondition(wReportCusAndVistEntity.getFundCondition());
//                    wReportCustomerEntity.setExistingDevice(wReportCusAndVistEntity.getExistingDevice());
//
//                    //保存客户信息：添加&修改
//                    WReportCustomerEntity oldWReportCustomerEntity = wReportCustomerDao.getByTel(wReportCustomerEntity.getTel());
//                    if (oldWReportCustomerEntity == null) {
//                        wReportCustomerDao.add(wReportCustomerEntity);
//                    } else {
//                        wReportCustomerEntity.setId(oldWReportCustomerEntity.getId());
//                        if (StringUtils.isBlank(oldWReportCustomerEntity.getCreateUserId())) {
//                            wReportCustomerEntity.setCreateUserId(wReportEntity.getMain().getUserId());
//                            wReportCustomerEntity.setCreateTime(wReportMainDao.getCurrentTime());
//                        } else {
//                            //判断该用户有没有离职
//                            JSONObject userJson = userDao.getViewJSONById(oldWReportCustomerEntity.getCreateUserId());
//                            String jobState=userJson.getString("jobState");
//                            if (!jobState.equals("1")){
//                                wReportCustomerEntity.setCreateUserId(oldWReportCustomerEntity.getCreateUserId());
//                                wReportCustomerEntity.setCreateTime(oldWReportCustomerEntity.getCreateTime());
//                            }else{
//                                wReportCustomerEntity.setCreateUserId(wReportEntity.getMain().getUserId());
//                                wReportCustomerEntity.setCreateTime(wReportMainDao.getCurrentTime());
//                            }
//
//                        }
//                        wReportCustomerDao.update(wReportCustomerEntity);
//                    }
//                    wReportCusVisitEntity.setCustomerId(wReportCustomerEntity.getId());
//                    wReportCusVisitEntity.setEntourage(wReportCusAndVistEntity.getEntourage());
//                    wReportCusVisitEntity.setVisitMode("1");
//                    wReportCusVisitEntity.setCompanyName(wReportCusAndVistEntity.getCompanyName());
//                    wReportCusVisitEntity.setVisitContent(wReportCusAndVistEntity.getVisitContent());
//                    wReportCusVisitEntity.setWId(wReportEntity.getMain().getId());
//                    wReportCusVisitEntity.setIntentionModel(wReportCusAndVistEntity.getIntentionModel());
//                    wReportCusVisitEntity.setBuyType(wReportCusAndVistEntity.getBuyType());
//                    wReportCusVisitEntity.setBuyDate(wReportCusAndVistEntity.getBuyDate());
//                    wReportCusVisitEntity.setFundCondition(wReportCusAndVistEntity.getFundCondition());
//
//                    wReportCusVisitEntity.setOtherCondition(wReportCusAndVistEntity.getOtherCondition());
//                    wReportCusVisitEntity.setExistingDevice(wReportCusAndVistEntity.getExistingDevice());
//
//                    wReportCusVisitEntity.setCreateUserId(wReportEntity.getMain().getUserId());
//                    wReportCusVisitEntity.setReportDate(wReportEntity.getMain().getReportDate());
//                    wReportCusVisitEntity.setArrivalsTime(wReportCusAndVistEntity.getArrivalsTime());
//                    wReportCusVisitEntity.setLeaveTime(wReportCusAndVistEntity.getLeaveTime());
//                    wReportCusVisitEntity.setLeaveImg(wReportCusAndVistEntity.getLeaveImg());
//                    wReportCusVisitEntity.setArrivalsLongitude(wReportCusAndVistEntity.getArrivalsLongitude());
//                    wReportCusVisitEntity.setArrivalsLatitude(wReportCusAndVistEntity.getArrivalsLatitude());
//                    wReportCusVisitEntity.setArrivalsAddress(wReportCusAndVistEntity.getArrivalsAddress());
//                    wReportCusVisitEntity.setLeaveLongitude(wReportCusAndVistEntity.getArrivalsLongitude());
//                    wReportCusVisitEntity.setLeaveLatitude(wReportCusAndVistEntity.getArrivalsLatitude());
//                    wReportCusVisitEntity.setLeaveAddress(wReportCusAndVistEntity.getLeaveAddress());
//                    wReportCusVisitEntity.setSysEntourage(wReportCusAndVistEntity.getSysEntourage());
//                    wReportCusVisitEntity.setSysEntourageId(wReportCusAndVistEntity.getSysEntourageId());
//                    //根据陪同人员姓名获取陪同人员Id
//                    JSONObject userJsonObject = userDao.getViewJSONByName(wReportCusAndVistEntity.getEntourage().trim());
//                    if (userJsonObject != null) {
//                        wReportCusVisitEntity.setEntourageId(userJsonObject.get("id").toString());
//                    }
//                    //获取写报告人员的公司id、区域id、大区id
//                    JSONObject userJson = userDao.getViewJSONById(wReportCusVisitEntity.getCreateUserId());
//                    if (userJson != null) {
//                        wReportCusVisitEntity.setCompanyId(userJson.get("companyId").toString());
//                        String roleName = userJson.get("roleName").toString();
//                        if (roleName.equals("区域经理")) {
//                            //获取区域id
//                            JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getCreateUserId(), " AND PARENT_ID != '0'");
//                            if (regionJson != null) {
//                                wReportCusVisitEntity.setRegionId(regionJson.get("id").toString());
//                            }
//                        }
//                        if (roleName.equals("区域经理") || roleName.equals("大区经理")) {
//                            //获取大区id
//                            JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getCreateUserId(), " AND PARENT_ID = '0'");
//                            if (regionJson != null) {
//                                wReportCusVisitEntity.setBigRegionId(regionJson.get("id").toString());
//                            }
//                        }
//                        //获取陪同人员的区域id
//                        JSONObject entourageUserJson = userDao.getViewJSONById(wReportCusVisitEntity.getEntourageId());
//                        if (entourageUserJson != null) {
//                            String entourageRoleName = entourageUserJson.get("roleName").toString();
//                            if (entourageRoleName.equals("区域经理")) {
//                                //获取区域id
//                                JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getEntourageId(), " AND PARENT_ID != '0'");
//                                if (regionJson != null) {
//                                    wReportCusVisitEntity.setEntourageRegionId(regionJson.get("id").toString());
//                                }
//                            } else if (entourageRoleName.equals("大区经理")) {
//                                //获取大区id
//                                JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getEntourageId(), " AND PARENT_ID = '0'");
//                                if (regionJson != null) {
//                                    wReportCusVisitEntity.setEntourageRegionId(regionJson.get("id").toString());
//                                }
//                            }
//                        }
//                    }
//                    wRportCusVisitDao.add(wReportCusVisitEntity);
//                }
//            }
//        }


        //当日拜访客户(拜访)
        if (wReportEntity.getTodayVisitCustomer() != null) {
            for (WReportCusAndVistEntity wReportCusAndVistEntity : wReportEntity.getTodayVisitCustomer()) {
                if (!StringUtils.isEmpty(wReportCusAndVistEntity.getTel())) {
                    WReportCustomerEntity wReportCustomerEntity = new WReportCustomerEntity();
                    WReportCusVisitEntity wReportCusVisitEntity = new WReportCusVisitEntity();
                    ThurTrackEntity thurTrackEntity=new ThurTrackEntity();
                    wReportCustomerEntity.setTel(wReportCusAndVistEntity.getTel().replaceAll(" ","").trim());
                    wReportCustomerEntity.setName(wReportCusAndVistEntity.getName());
                    wReportCustomerEntity.setCompanyName(wReportCusAndVistEntity.getCompanyName());
                    wReportCustomerEntity.setCustomerCredit(wReportCusAndVistEntity.getCustomerCredit());
                    wReportCustomerEntity.setCustomerLevel(wReportCusAndVistEntity.getCustomerLevel());
                    wReportCustomerEntity.setCustomerType(wReportCusAndVistEntity.getCustomerType());
                    //wReportCustomerEntity.setBirthday(wReportCusAndVistEntity.getBirthDay());
                    wReportCustomerEntity.setBuildProvinceName(wReportCusAndVistEntity.getBuildProvinceName());
                    wReportCustomerEntity.setBuildCityName(wReportCusAndVistEntity.getBuildCityName());
                    wReportCustomerEntity.setBuildCountyName(wReportCusAndVistEntity.getBuildCountyName());
                    wReportCustomerEntity.setBuildProvinceId(wReportCusAndVistEntity.getBuildProvinceId());
                    wReportCustomerEntity.setBuildCityId(wReportCusAndVistEntity.getBuildCityId());
                    wReportCustomerEntity.setBuildCityId(wReportCusAndVistEntity.getBuildCountyId());
                    wReportCustomerEntity.setCreateUserId(wReportEntity.getMain().getUserId());
                    wReportCustomerEntity.setSource(wReportCusAndVistEntity.getSource());
                    if (wReportCusAndVistEntity.getIntentionModel()!=null&&!wReportCusAndVistEntity.getIntentionModel().equals("型号")){
                        wReportCustomerEntity.setIntentionModel(wReportCusAndVistEntity.getIntentionModel());
                    }else{
                        wReportCustomerEntity.setIntentionModel("");
                    }
                    if (wReportCusAndVistEntity.getIntentionDevice()!=null&&!wReportCusAndVistEntity.getIntentionDevice().equals("设备类型")){
                        wReportCustomerEntity.setIntentionDevice(wReportCusAndVistEntity.getIntentionDevice());
                    }else{
                        wReportCustomerEntity.setIntentionDevice("");
                    }
                    if (wReportCusAndVistEntity.getIntentionBrand()!=null&&!wReportCusAndVistEntity.getIntentionBrand().equals("品牌")){
                        wReportCustomerEntity.setIntentionBrand(wReportCusAndVistEntity.getIntentionBrand());
                    }else{
                        wReportCustomerEntity.setIntentionBrand("");
                    }

                    wReportCustomerEntity.setBuyType(wReportCusAndVistEntity.getBuyType());
                    wReportCustomerEntity.setBuyDate(wReportCusAndVistEntity.getBuyDate());
                    wReportCustomerEntity.setOtherCondition(wReportCusAndVistEntity.getOtherCondition());
                    wReportCustomerEntity.setServerCondition(wReportCusAndVistEntity.getServerCondition());
                    wReportCustomerEntity.setOtherVisitType(wReportCusAndVistEntity.getOtherVisitType());
                    wReportCustomerEntity.setAccessoriesChargesCondition(wReportCusAndVistEntity.getAccessoriesChargesCondition());
                    wReportCustomerEntity.setHoursChargesCondition(wReportCusAndVistEntity.getHoursChargesCondition());
                    wReportCustomerEntity.setSerialNo(wReportCusAndVistEntity.getSerialNo());

                    wReportCustomerEntity.setDebtCondition(wReportCusAndVistEntity.getDebtCondition());
                    wReportCustomerEntity.setLettersCondition(wReportCusAndVistEntity.getLettersCondition());
                    wReportCustomerEntity.setServerCustomerType(wReportCusAndVistEntity.getServerCustomerType());

                    wReportCustomerEntity.setFundCondition(wReportCusAndVistEntity.getFundCondition());
                    wReportCustomerEntity.setExistingDevice(wReportCusAndVistEntity.getExistingDevice());
                    wReportCustomerEntity.setType(wReportCusAndVistEntity.getType());
                    wReportCustomerEntity.setDeviceInfo(wReportCusAndVistEntity.getDeviceInfo());
                    wReportCustomerEntity.setDeviceHour(wReportCusAndVistEntity.getDeviceHour());
                    wReportCustomerEntity.setMachineNo(wReportCusAndVistEntity.getMachineNo());
                    wReportCustomerEntity.setChance(wReportCusAndVistEntity.getChance());


//                    //通过概率时间做商机确定时间预判
//                    //获取当前时间
//                    Date nowDate=new Date();
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd");
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.setTime(nowDate);
//
//                    // add方法中的第二个参数n中，正数表示该日期后n天，负数表示该日期的前n天
//                    if (wReportCustomerEntity.getBuyDate().equals("一周内")){
//                        calendar.add(Calendar.DATE, 5);
//                    }else if (wReportCustomerEntity.getBuyDate().equals("一月内")){
//                        calendar.add(Calendar.DATE, 25);
//                    }else{
//                        calendar.add(Calendar.DATE, 40);
//                    }
//                    //当前日期年月
//                    String nowYear=String.valueOf( nowDate.getYear()+1900);
//                    String nowMonth=String.valueOf(nowDate.getMonth()+1);
//                    //获取到日期类型的预测日期
//                    Date ycDate = calendar.getTime();
//                    //预测的年月
//                    String ycYear=String.valueOf( ycDate.getYear()+1900);
//                    String ycMonth=String.valueOf(ycDate.getMonth()+1);
//                    if (wReportCusAndVistEntity.getChance().equals("100%")){
//                        if ((nowDate.getMonth()+1)!=(ycDate.getMonth()+1)){
//                            wReportCustomerEntity.setBusinessDate(nowYear+"年"+nowMonth+"月下旬");
//                            wReportCusVisitEntity.setBusinessDate(nowYear+"年"+nowMonth+"月下旬");
//                        }else{
//                            if (ycDate.getDate()<=10){
//                                wReportCustomerEntity.setBusinessDate(nowYear+"年"+nowMonth+"月上旬");
//                                wReportCusVisitEntity.setBusinessDate(nowYear+"年"+nowMonth+"月上旬");
//                            }else if (ycDate.getDate()>10&&ycDate.getDate()<=20){
//                                wReportCustomerEntity.setBusinessDate(nowYear+"年"+nowMonth+"月中旬");
//                                wReportCusVisitEntity.setBusinessDate(nowYear+"年"+nowMonth+"月中旬");
//                            }else{
//                                wReportCustomerEntity.setBusinessDate(nowYear+"年"+nowMonth+"月下旬");
//                                wReportCusVisitEntity.setBusinessDate(nowYear+"年"+nowMonth+"月下旬");
//                            }
//                        }
//                    }else{
//                        if (ycDate.getDate()<=10){
//                            wReportCustomerEntity.setBusinessDate(ycYear+"年"+ycMonth+"月上旬");
//                            wReportCusVisitEntity.setBusinessDate(ycYear+"年"+ycMonth+"月上旬");
//
//                        }else if (ycDate.getDate()>10&&ycDate.getDate()<=20){
//                            wReportCustomerEntity.setBusinessDate(ycYear+"年"+ycMonth+"月中旬");
//                            wReportCusVisitEntity.setBusinessDate(ycYear+"年"+ycMonth+"月中旬");
//
//                        }else{
//                            wReportCustomerEntity.setBusinessDate(ycYear+"年"+ycMonth+"月下旬");
//                            wReportCusVisitEntity.setBusinessDate(ycYear+"年"+ycMonth+"月下旬");
//
//                        }
//                    }
                    //保存客户信息：添加&修改
                    WReportCustomerEntity oldWReportCustomerEntity = wReportCustomerDao.getByTel(wReportCustomerEntity.getTel());
                    if (oldWReportCustomerEntity == null) {
                        if (!StringUtils.isBlank(wReportCusAndVistEntity.getIntentionModel())
                                &&!wReportCusAndVistEntity.getIntentionModel().equals("无")
                                &&!wReportCusAndVistEntity.getIntentionModel().equals("暂无")
                                &&!wReportCusAndVistEntity.getIntentionModel().equals("型号")
                                &&wReportCusAndVistEntity.getServerCondition().equals("")) {
                            wReportCustomerEntity.setIntentionTime(wReportMainDao.getCurrentTime());
                            wReportCustomerEntity.setIntentionFlag(1);
                        } else {
                            wReportCustomerEntity.setIntentionFlag(0);
                        }
                        wReportCustomerDao.add(wReportCustomerEntity);
                    } else {
                        wReportCustomerEntity.setId(oldWReportCustomerEntity.getId());
                        if (StringUtils.isBlank(oldWReportCustomerEntity.getCreateUserId())) {
                            wReportCustomerEntity.setCreateUserId(wReportEntity.getMain().getUserId());
                            wReportCustomerEntity.setCreateTime(wReportMainDao.getCurrentTime());
                        } else {
                            //判断该用户有没有离职
                            JSONObject userJson = userDao.getViewJSONById(oldWReportCustomerEntity.getCreateUserId());
                            String jobState = userJson.getString("jobState");
                            if (!jobState.equals("1")) {
                                wReportCustomerEntity.setCreateUserId(oldWReportCustomerEntity.getCreateUserId());
                                wReportCustomerEntity.setCreateTime(oldWReportCustomerEntity.getCreateTime());
                            } else {
                                wReportCustomerEntity.setCreateUserId(wReportEntity.getMain().getUserId());
                                wReportCustomerEntity.setCreateTime(wReportMainDao.getCurrentTime());
                            }
                        }
                            if (!StringUtils.isBlank(wReportCusAndVistEntity.getIntentionModel())
                                    &&!wReportCusAndVistEntity.getIntentionModel().equals("无")
                                    &&!wReportCusAndVistEntity.getIntentionModel().equals("暂无")
                                    &&!wReportCusAndVistEntity.getIntentionModel().equals("型号")
                                    &&wReportCusAndVistEntity.getServerCondition().equals("")) {
                                if (oldWReportCustomerEntity.getIntentionTime() == null || oldWReportCustomerEntity.getIntentionFlag() != 1) {
                                    wReportCustomerEntity.setIntentionTime(wReportMainDao.getCurrentTime());
                                    wReportCustomerEntity.setIntentionFlag(1);
                                }

                            }

                        wReportCustomerDao.update(wReportCustomerEntity);
                    }
                    wReportCusVisitEntity.setCustomerId(wReportCustomerEntity.getId());
                    wReportCusVisitEntity.setCompanyName(wReportCusAndVistEntity.getCompanyName());
                    wReportCusVisitEntity.setCustomerBackground(wReportCusAndVistEntity.getCustomerBackground());
                    wReportCusVisitEntity.setRevenueForecast(wReportCusAndVistEntity.getRevenueForecast());
                    wReportCusVisitEntity.setEquipmentUse(wReportCusAndVistEntity.getEquipmentUse());
                    wReportCusVisitEntity.setCustomerCredit(wReportCusAndVistEntity.getCustomerCredit());
                    wReportCusVisitEntity.setCustomerLevel(wReportCusAndVistEntity.getCustomerLevel());
                    wReportCusVisitEntity.setCustomerType(wReportCusAndVistEntity.getCustomerType());
                    wReportCusVisitEntity.setEntourage(wReportCusAndVistEntity.getEntourage());
                    wReportCusVisitEntity.setEntourageId(wReportCusAndVistEntity.getEntourageId());
                    wReportCusVisitEntity.setVisitMode(wReportCusAndVistEntity.getVisitMode());
                    wReportCusVisitEntity.setVisitContent(wReportCusAndVistEntity.getVisitContent());
                    wReportCusVisitEntity.setwId(wReportEntity.getMain().getId());
                    wReportCusVisitEntity.setIntentionModel(wReportCusAndVistEntity.getIntentionModel());
                    wReportCusVisitEntity.setIntentionDevice(wReportCusAndVistEntity.getIntentionDevice());
                    wReportCusVisitEntity.setIntentionBrand(wReportCusAndVistEntity.getIntentionBrand());
                    wReportCusVisitEntity.setBuyType(wReportCusAndVistEntity.getBuyType());
                    wReportCusVisitEntity.setBuyDate(wReportCusAndVistEntity.getBuyDate());
                    wReportCusVisitEntity.setFundCondition(wReportCusAndVistEntity.getFundCondition());
                    wReportCusVisitEntity.setType(wReportCusAndVistEntity.getType());
                    wReportCusVisitEntity.setArrivalsImg(wReportCusAndVistEntity.getArrivalsImg());
                    wReportCusVisitEntity.setOtherCondition(wReportCusAndVistEntity.getOtherCondition());
                    wReportCusVisitEntity.setServerCondition(wReportCusAndVistEntity.getServerCondition());
                    wReportCusVisitEntity.setOtherVisitType(wReportCusAndVistEntity.getOtherVisitType());
                    wReportCusVisitEntity.setAccessoriesChargesCondition(wReportCusAndVistEntity.getAccessoriesChargesCondition());
                    wReportCusVisitEntity.setHoursChargesCondition(wReportCusAndVistEntity.getHoursChargesCondition());
                    wReportCusVisitEntity.setSerialNo(wReportCusAndVistEntity.getSerialNo());

                    wReportCusVisitEntity.setDebtCondition(wReportCusAndVistEntity.getDebtCondition());
                    wReportCusVisitEntity.setLettersCondition(wReportCusAndVistEntity.getLettersCondition());
                    wReportCusVisitEntity.setServerCustomerType(wReportCusAndVistEntity.getServerCustomerType());
                    wReportCusVisitEntity.setChance(wReportCusAndVistEntity.getChance());

                    wReportCusVisitEntity.setExistingDevice(wReportCusAndVistEntity.getExistingDevice());

                    wReportCusVisitEntity.setCreateUserId(wReportEntity.getMain().getUserId());
                    wReportCusVisitEntity.setReportDate(wReportEntity.getMain().getReportDate());
                    wReportCusVisitEntity.setArrivalsTime(wReportCusAndVistEntity.getArrivalsTime());
                    wReportCusVisitEntity.setLeaveTime(wReportCusAndVistEntity.getLeaveTime());
                    wReportCusVisitEntity.setLeaveImg(wReportCusAndVistEntity.getLeaveImg());
                    wReportCusVisitEntity.setArrivalsLongitude(wReportCusAndVistEntity.getArrivalsLongitude());
                    wReportCusVisitEntity.setArrivalsLatitude(wReportCusAndVistEntity.getArrivalsLatitude());
                    wReportCusVisitEntity.setArrivalsAddress(wReportCusAndVistEntity.getArrivalsAddress());
                    wReportCusVisitEntity.setLeaveLongitude(wReportCusAndVistEntity.getArrivalsLongitude());
                    wReportCusVisitEntity.setLeaveLatitude(wReportCusAndVistEntity.getArrivalsLatitude());
                    wReportCusVisitEntity.setLeaveAddress(wReportCusAndVistEntity.getLeaveAddress());
                    wReportCusVisitEntity.setSysEntourage(wReportCusAndVistEntity.getSysEntourage());
                    wReportCusVisitEntity.setSysEntourageId(wReportCusAndVistEntity.getSysEntourageId());
                    wReportCusVisitEntity.setDeviceInfo(wReportCusAndVistEntity.getDeviceInfo());
                    wReportCusVisitEntity.setDeviceHour(wReportCusAndVistEntity.getDeviceHour());
                    wReportCusVisitEntity.setMachineNo(wReportCusAndVistEntity.getMachineNo());
                    wReportCusVisitEntity.setFeeDesc(wReportCusAndVistEntity.getFeeDesc());
                    wReportCusVisitEntity.setFeeType(wReportCusAndVistEntity.getFeeType());
                    if (!StringUtils.isBlank(wReportCusAndVistEntity.getIntentionModel())
                            &&!wReportCusAndVistEntity.getIntentionModel().equals("无")
                            &&!wReportCusAndVistEntity.getIntentionModel().equals("暂无")
                            &&!wReportCusAndVistEntity.getIntentionModel().equals("型号")
                            &&wReportCusAndVistEntity.getServerCondition().equals("")) {
                        wReportCusVisitEntity.setIntentionTime(wReportMainDao.getCurrentTime());
                        wReportCusVisitEntity.setIntentionFlag(1);
                    }

                    //获取写报告人员的公司id、区域id、大区id
                    JSONObject userJson = userDao.getViewJSONById(wReportCusVisitEntity.getCreateUserId());
                    if (userJson != null) {
                        wReportCusVisitEntity.setCompanyId(userJson.get("companyId").toString());
                        String roleName = userJson.get("roleName").toString();
                        if (roleName.equals("区域经理")) {
                            String bigRegionManager=userDao.getFirstParent(wReportCusVisitEntity.getCreateUserId()).getString("name");
                            thurTrackEntity.setRegionalManagerId(wReportCusVisitEntity.getCreateUserId());
                            thurTrackEntity.setRegionalManagerName(userJson.getString("name"));
                            thurTrackEntity.setCompanyId(userJson.getString("companyId"));
                            thurTrackEntity.setCompanyName(userJson.getString("companyName"));
                            thurTrackEntity.setBigRegionalId(userJson.getString("departId"));
                            thurTrackEntity.setBigRegionalManagerName(bigRegionManager);
                            thurTrackEntity.setCustomerTel(wReportCusAndVistEntity.getTel().replaceAll(" ","").trim());
                            thurTrackEntity.setCustomerName(wReportCusAndVistEntity.getName());
                            thurTrackEntity.setBuyType(wReportCusAndVistEntity.getBuyType());
                            thurTrackEntity.setNeedModel(wReportCusAndVistEntity.getIntentionModel());
                            thurTrackEntity.setBuildCondition(wReportCusAndVistEntity.getOtherCondition());
                            thurTrackEntity.setNeedNumber(1);
                            thurTrackEntity.setAuditFlag("-1");
                            thurTrackEntity.setCustomerId(wReportCustomerEntity.getId());
                            if (!StringUtils.isBlank(wReportCusAndVistEntity.getIntentionModel())
                                    &&!wReportCusAndVistEntity.getIntentionModel().equals("无")
                                    &&!wReportCusAndVistEntity.getIntentionModel().equals("暂无")
                                    &&!wReportCusAndVistEntity.getIntentionModel().equals("型号")
                                    &&wReportCusAndVistEntity.getServerCondition().equals("")) {
                                List<JSONObject> sjCustomer=thurTrackDao.getJSONListByCondition(" and CUSTOMER_TEL=? ",new Object[]{wReportCusAndVistEntity.getTel()});
                                if (null!=sjCustomer&&sjCustomer.size()>0){
                                }else{
                                    thurTrackDao.add(thurTrackEntity);
                                }
                            }
                            //获取区域id
                            JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getCreateUserId(), " AND PARENT_ID != '0'");
                            if (regionJson != null) {
                                wReportCusVisitEntity.setRegionId(regionJson.get("id").toString());
                                thurTrackEntity.setRegionalId(regionJson.get("id").toString());
                            }
                        }
                        if (roleName.equals("区域经理") || roleName.equals("大区经理")) {
                            //获取大区id
                            JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getCreateUserId(), " AND PARENT_ID = '0'");
                            if (regionJson != null) {
                                wReportCusVisitEntity.setBigRegionId(regionJson.get("id").toString());
                            }
                        }
                        //获取陪同人员的区域id
                        JSONObject entourageUserJson = userDao.getViewJSONById(wReportCusVisitEntity.getEntourageId());
                        if (entourageUserJson != null) {
                            String entourageRoleName = entourageUserJson.get("roleName").toString();
                            if (entourageRoleName.equals("区域经理")) {
                                //获取区域id
                                JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getEntourageId(), " AND PARENT_ID != '0'");
                                if (regionJson != null) {
                                    wReportCusVisitEntity.setEntourageRegionId(regionJson.get("id").toString());
                                }
                            } else if (entourageRoleName.equals("大区经理")) {
                                //获取大区id
                                JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getEntourageId(), " AND PARENT_ID = '0'");
                                if (regionJson != null) {
                                    wReportCusVisitEntity.setEntourageRegionId(regionJson.get("id").toString());
                                }
                            }
                        }
                    }


                    wRportCusVisitDao.add(wReportCusVisitEntity);
                }
            }
        }
        //当日拜访客户(电访)
//        if (wReportEntity.getTodayCustomerTelVisit() != null) {
//            for (WReportCusAndVistEntity wReportCusAndVistEntity : wReportEntity.getTodayCustomerTelVisit()) {
//                if (!StringUtils.isEmpty(wReportCusAndVistEntity.getTel())) {
//                    WReportCustomerEntity wReportCustomerEntity = new WReportCustomerEntity();
//                    WReportCusVisitEntity wReportCusVisitEntity = new WReportCusVisitEntity();
//                    wReportCustomerEntity.setTel(wReportCusAndVistEntity.getTel());
//                    wReportCustomerEntity.setName(wReportCusAndVistEntity.getName());
//                    wReportCustomerEntity.setCompanyName(wReportCusAndVistEntity.getCompanyName());
//                 //   wReportCustomerEntity.setBirthday(wReportCusAndVistEntity.getBirthDay());
//                    wReportCustomerEntity.setBuildProvinceName(wReportCusAndVistEntity.getBuildProvinceName());
//                    wReportCustomerEntity.setBuildCityName(wReportCusAndVistEntity.getBuildCityName());
//                    wReportCustomerEntity.setBuildCountyName(wReportCusAndVistEntity.getBuildCountyName());
//                    wReportCustomerEntity.setBuildProvinceId(wReportCusAndVistEntity.getBuildProvinceId());
//                    wReportCustomerEntity.setBuildCityId(wReportCusAndVistEntity.getBuildCityId());
//                    wReportCustomerEntity.setBuildCityId(wReportCusAndVistEntity.getBuildCountyId());
//                    wReportCustomerEntity.setCreateUserId(wReportEntity.getMain().getUserId());
//                    wReportCustomerEntity.setSource(wReportCusAndVistEntity.getSource());
//                    wReportCustomerEntity.setIntentionModel(wReportCusAndVistEntity.getIntentionModel());
//                    wReportCustomerEntity.setBuyType(wReportCusAndVistEntity.getBuyType());
//                    wReportCustomerEntity.setBuyDate(wReportCusAndVistEntity.getBuyDate());
//
//                    wReportCustomerEntity.setOtherCondition(wReportCusAndVistEntity.getOtherCondition());
//                    wReportCustomerEntity.setFundCondition(wReportCusAndVistEntity.getFundCondition());
//                    wReportCustomerEntity.setExistingDevice(wReportCusAndVistEntity.getExistingDevice());
//
//
//                    //保存客户信息：添加&修改
//                    WReportCustomerEntity oldWReportCustomerEntity = wReportCustomerDao.getByTel(wReportCustomerEntity.getTel());
//                    if (oldWReportCustomerEntity == null) {
//                        wReportCustomerDao.add(wReportCustomerEntity);
//                    } else {
//                        wReportCustomerEntity.setId(oldWReportCustomerEntity.getId());
//                        if (StringUtils.isBlank(oldWReportCustomerEntity.getCreateUserId())) {
//                            wReportCustomerEntity.setCreateUserId(wReportEntity.getMain().getUserId());
//                            wReportCustomerEntity.setCreateTime(wReportMainDao.getCurrentTime());
//                        } else {
//                            //判断该用户有没有离职
//                            JSONObject userJson = userDao.getViewJSONById(oldWReportCustomerEntity.getCreateUserId());
//                            String jobState=userJson.getString("jobState");
//                            if (!jobState.equals("1")){
//                                wReportCustomerEntity.setCreateUserId(oldWReportCustomerEntity.getCreateUserId());
//                                wReportCustomerEntity.setCreateTime(oldWReportCustomerEntity.getCreateTime());
//                            }else{
//                                wReportCustomerEntity.setCreateUserId(wReportEntity.getMain().getUserId());
//                                wReportCustomerEntity.setCreateTime(wReportMainDao.getCurrentTime());
//                            }
//
//                        }
//                        wReportCustomerDao.update(wReportCustomerEntity);
//                    }
//                    wReportCusVisitEntity.setCustomerId(wReportCustomerEntity.getId());
//                    wReportCusVisitEntity.setCompanyName(wReportCusAndVistEntity.getCompanyName());
//                    wReportCusVisitEntity.setEntourage(wReportCusAndVistEntity.getEntourage());
//                    wReportCusVisitEntity.setVisitMode("0");
//                    wReportCusVisitEntity.setVisitContent(wReportCusAndVistEntity.getVisitContent());
//                    wReportCusVisitEntity.setWId(wReportEntity.getMain().getId());
//                    wReportCusVisitEntity.setIntentionModel(wReportCusAndVistEntity.getIntentionModel());
//                    wReportCusVisitEntity.setBuyType(wReportCusAndVistEntity.getBuyType());
//                    wReportCusVisitEntity.setBuyDate(wReportCusAndVistEntity.getBuyDate());
//                    wReportCusVisitEntity.setFundCondition(wReportCusAndVistEntity.getFundCondition());
//
//                    wReportCusVisitEntity.setOtherCondition(wReportCusAndVistEntity.getOtherCondition());
//                    wReportCusVisitEntity.setExistingDevice(wReportCusAndVistEntity.getExistingDevice());
//
//
//                    wReportCusVisitEntity.setCreateUserId(wReportEntity.getMain().getUserId());
//                    wReportCusVisitEntity.setReportDate(wReportEntity.getMain().getReportDate());
//                    wReportCusVisitEntity.setArrivalsTime(wReportCusAndVistEntity.getArrivalsTime());
//                    wReportCusVisitEntity.setLeaveTime(wReportCusAndVistEntity.getLeaveTime());
//                    wReportCusVisitEntity.setLeaveImg(wReportCusAndVistEntity.getLeaveImg());
//                    wReportCusVisitEntity.setArrivalsLongitude(wReportCusAndVistEntity.getArrivalsLongitude());
//                    wReportCusVisitEntity.setArrivalsLatitude(wReportCusAndVistEntity.getArrivalsLatitude());
//                    wReportCusVisitEntity.setArrivalsAddress(wReportCusAndVistEntity.getArrivalsAddress());
//                    wReportCusVisitEntity.setLeaveLongitude(wReportCusAndVistEntity.getArrivalsLongitude());
//                    wReportCusVisitEntity.setLeaveLatitude(wReportCusAndVistEntity.getArrivalsLatitude());
//                    wReportCusVisitEntity.setLeaveAddress(wReportCusAndVistEntity.getLeaveAddress());
//                    wReportCusVisitEntity.setSysEntourage(wReportCusAndVistEntity.getSysEntourage());
//                    wReportCusVisitEntity.setSysEntourageId(wReportCusAndVistEntity.getSysEntourageId());
//                    //根据陪同人员姓名获取陪同人员Id
//                    JSONObject userJsonObject = userDao.getViewJSONByName(wReportCusAndVistEntity.getEntourage().trim());
//                    if (userJsonObject != null) {
//                        wReportCusVisitEntity.setEntourageId(userJsonObject.get("id").toString());
//                    }
//                    //获取写报告人员的公司id、区域id、大区id
//                    JSONObject userJson = userDao.getViewJSONById(wReportCusVisitEntity.getCreateUserId());
//                    if (userJson != null) {
//                        wReportCusVisitEntity.setCompanyId(userJson.get("companyId").toString());
//                        String roleName = userJson.get("roleName").toString();
//                        if (roleName.equals("区域经理")) {
//                            //获取区域id
//                            JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getCreateUserId(), " AND PARENT_ID != '0'");
//                            if (regionJson != null) {
//                                wReportCusVisitEntity.setRegionId(regionJson.get("id").toString());
//                            }
//                        }
//                        if (roleName.equals("区域经理") || roleName.equals("大区经理")) {
//                            //获取大区id
//                            JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getCreateUserId(), " AND PARENT_ID = '0'");
//                            if (regionJson != null) {
//                                wReportCusVisitEntity.setBigRegionId(regionJson.get("id").toString());
//                            }
//                        }
//                        //获取陪同人员的区域id
//                        JSONObject entourageUserJson = userDao.getViewJSONById(wReportCusVisitEntity.getEntourageId());
//                        if (entourageUserJson != null) {
//                            String entourageRoleName = entourageUserJson.get("roleName").toString();
//                            if (entourageRoleName.equals("区域经理")) {
//                                //获取区域id
//                                JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getEntourageId(), " AND PARENT_ID != '0'");
//                                if (regionJson != null) {
//                                    wReportCusVisitEntity.setEntourageRegionId(regionJson.get("id").toString());
//                                }
//                            } else if (entourageRoleName.equals("大区经理")) {
//                                //获取大区id
//                                JSONObject regionJson = regionDao.getRegionByRoleName(wReportCusVisitEntity.getEntourageId(), " AND PARENT_ID = '0'");
//                                if (regionJson != null) {
//                                    wReportCusVisitEntity.setEntourageRegionId(regionJson.get("id").toString());
//                                }
//                            }
//                        }
//                    }
//                    wRportCusVisitDao.add(wReportCusVisitEntity);
//                }
//            }
//        }
        //当日费用明细
        if (wReportEntity.getTodayCostDetail() != null) {
            for (WReportCostEntity wReportCostEntity : wReportEntity.getTodayCostDetail()) {
                wReportCostEntity.setwId(wId);
                wReportCostEntity.setStart(0);
                String auditFlag = costAuditDao.getAuditFlag(wReportCostEntity.getId()).getString("auditFlag");
                wReportCostEntity.setAuditFlag(auditFlag);
                wReportCostDao.update(wReportCostEntity);
            }
        }
        //当日费用明细
        if (wReportEntity.getTodayCostDetail2() != null) {
            for (WReportCostEntity wReportCostEntity : wReportEntity.getTodayCostDetail2()) {
                if (wReportCostEntity.getMoney() != null) {
                    wReportCostEntity.setwId(wId);
                    wReportCostEntity.setStart(0);
                    wReportCostEntity.setCreateUserId(wReportEntity.getMain().getUserId());
                    wReportCostEntity.setReportDate(wReportEntity.getMain().getReportDate());
                    wReportCostDao.add(wReportCostEntity);
                }


            }
        }
        //删除工作报告第二天拜访计划

        tomorrowVisitDao.removeByCondition("AND CREATE_USER_ID=? AND REPORT_DATE=?",
                new String[]{wReportEntity.getMain().getUserId(), wReportEntity.getMain().getReportDate()});
        //第二天拜访计划
        if (wReportEntity.getTomorrowVisitPlan() != null) {
            for (TomorrowVisitPlanEntity tomorrowVisitPlanEntity : wReportEntity.getTomorrowVisitPlan()) {
                if (StringUtils.isNotEmpty(tomorrowVisitPlanEntity.getCustomerName())){
                    tomorrowVisitPlanEntity.setwId(wId);
                    tomorrowVisitPlanEntity.setReportDate(wReportEntity.getMain().getReportDate());
                    tomorrowVisitDao.add(tomorrowVisitPlanEntity);
                }
            }
        }
        //下属当日工作情况描述
        if (wReportEntity.getJobDescriptionForBranch() != null) {
            for (WReportBranchEntity wReportBranchEntity : wReportEntity.getJobDescriptionForBranch()) {
                wReportBranchEntity.setwId(wId);
                wReportBranchDao.add(wReportBranchEntity);
            }
        }
        //当日收款情况
        if (wReportEntity.getTodayGatherSituation() != null) {
            for (WReportGatherEntity wReportGatherEntity : wReportEntity.getTodayGatherSituation()) {
                wReportGatherEntity.setwId(wId);
                wReportGatherDao.add(wReportGatherEntity);
            }
        }
        if (wReportEntity.getMain().getFlage().equals("0")) {
            //发送邮件

            EmailEntity emailEntity = new EmailEntity();

            //邮件主表
            EmailMainEntity mains = new EmailMainEntity();
            String title = wReportEntity.getMain().getTitle();
            mains.setSubject(title);
            mains.setContent("");
            mains.setCreateUserId(wReportEntity.getMain().getUserId());
            mains.setEtype(1);
            mains.setDataId(wReportEntity.getMain().getId());
            mains.setParentId("");
            mains.setDraft(0);
            mains.setUpdateUserId(wReportEntity.getMain().getUserId());
            mains.setReportDate(wReportEntity.getMain().getReportDate());
            emailEntity.setMains(mains);
            emailEntity.setType("0");
            emailEntity.setReceivers(wReportEntity.getReceivers());//张三，李四
            emailEntity.setCopiers(wReportEntity.getCopiers());//张三
            emailEntity.setHandAddReceivers(wReportEntity.getHandAddReceivers());
            emailEntity.setHandAddCopiers(wReportEntity.getHandAddCopiers());
            JSONObject object = FastJsonConvert.convertObjectToJSONObject(emailEntity);
            String emailId = emailService.sendEmail(object.toJSONString());
        }
        return wReportEntity.getMain().getId();
    }

    @Override
    public JSONObject getByUserIdAndReportDate(String userId, String reportDate) {
        WReportEntity wReportEntity = new WReportEntity();
        String CostSmallId = "";
        WReportMainEntity main = wReportMainDao.getByUserIdAndReportDate(userId, reportDate);
        //收件人
        //wReportEntity.setReceivers(new ArrayList<>());
        //抄送人
        //wReportEntity.setCopiers(new ArrayList<>());

        if (main != null) {
            wReportEntity.setMain(main);
            getLoadWReport(userId, reportDate, wReportEntity);
            setWReportEntity(wReportEntity);
        } else {
            List<WReportUnfinishEntity> wReportUnfinishEntities = new ArrayList<>();
            String date = "";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!StringUtils.isBlank(reportDate)) {
                try {
                    date = DateUtils.getBeforeDate(sdf.parse(reportDate), 1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                date = DateUtils.getYesterday();
            }
            WReportMainEntity wReportMainEntity = wReportMainDao.getByUserIdAndReportDate(userId, date);
            if (wReportMainEntity != null) {
                wReportUnfinishEntities = wReportUnfinishDao.getFinishEntityListByCondition(" and TYPE= '3' AND W_ID=?  ", new Object[]{wReportMainEntity.getId()});
                wReportEntity.setUnfinishes(wReportUnfinishEntities);
            }

            //写报告时带出某些模块
            getLoadWReport(userId, reportDate, wReportEntity);
        }
        return (JSONObject) JSON.toJSON(wReportEntity);
    }

    @Override
    public JSONObject getReceiverAndCopiers(String userId) {
        JSONObject objResult = new JSONObject();
        JSONArray arrReceivers = new JSONArray();
        JSONArray arrCopiers = new JSONArray();
        JSONArray arrHandAddReceivers = new JSONArray();
        JSONArray arrHandAddCopiers = new JSONArray();
        String supportUserId = "";
        String parentUserId = "";
        String jjParentUserId = "";
        StringBuffer sbCondition = new StringBuffer();
        JSONObject jsonObject = userDao.getViewJSONById(userId);
        Integer frontFlag = null;
        if (jsonObject != null) {
            frontFlag = jsonObject.getInteger("frontFlag");
        }

        //获取收件人（直接上级）
        JSONObject parent = userDao.getFirstParent(userId);
        if (parent != null) {
            JSONObject receiver = new JSONObject();
            receiver.put("userId", parent.getString("id"));
            receiver.put("userName", parent.getString("name"));
            parentUserId = parent.getString("id");
            arrReceivers.add(receiver);
        }
        if (!"服务部".equals(jsonObject.getString("departName"))&&!"201712161613432EAF27DBCCB7D0E6CA".equals(jsonObject.getString("companyId"))) {
            if (frontFlag == 1) {
                //获取收件人（区域支持）
                JSONObject support = userDao.getSupportByUserId(userId);
                if (support != null) {
                    JSONObject receiver = new JSONObject();
                    receiver.put("userId", support.getString("id"));
                    receiver.put("userName", support.getString("name"));
                    supportUserId = support.getString("id");
                    arrReceivers.add(receiver);
                }
            }
        }
        //获取抄送人（间接上级）
        List<JSONObject> secondhandParent = this.getParentList(userId);
        for (int i = 0; i < secondhandParent.size(); i++) {
            JSONObject copier = new JSONObject();
            if (!StringUtils.isBlank(secondhandParent.get(i).getString("id"))) {
                copier.put("userId", secondhandParent.get(i).getString("id"));
                copier.put("userName", secondhandParent.get(i).getString("name"));
                jjParentUserId= jjParentUserId+"'"+secondhandParent.get(i).getString("id")+"',";
                arrCopiers.add(copier);
            }

        }
        if(StringUtils.isBlank(jjParentUserId)){
            jjParentUserId="''";
        }else{
            jjParentUserId=jjParentUserId.substring(0,jjParentUserId.length()-1);

        }
        if("201712161851433BAD8487BE30159C9E".equals(userId)){
                JSONObject copier = new JSONObject();
                copier.put("userId","201711271733404C9DA1461F2421F828" );
                copier.put("userName","曹国玉");
                arrCopiers.add(copier);
        }else{
            if ("2017121910424ED9AA4F786D5549D72F".equalsIgnoreCase(jsonObject.getString("companyId"))){
                JSONObject copier = new JSONObject();
                copier.put("userId", "201712161851433BAD8487BE30159C9E");
                copier.put("userName", "贾贤达");
                arrCopiers.add(copier);
            }else {
                sbCondition.append(" AND v_sys_part_time_for_report.userId NOT in('" + userId + "','" + supportUserId + "','" + parentUserId + "','2017121618514C22B68296F31AF8DDE2',"+jjParentUserId+")\n");

            }
        //获取抄送人（支持类）
        List<JSONObject> secondhandSupport = userDao.getSupportUserList(userId, sbCondition.toString());
        for (int i = 0; i < secondhandSupport.size(); i++) {
            arrCopiers.add(secondhandSupport.get(i));
             }
        }
        //获取手动填写的收件人

        List<JSONObject> handAddReceivers = wreportReceiverCopiersDao.getJSONListByCondition(" and sender_user_id=? and type=0", new Object[]{userId});

        for (int i = 0; i < handAddReceivers.size(); i++) {
            JSONObject handAddReceiver = new JSONObject();
            if (!StringUtils.isBlank(handAddReceivers.get(i).getString("userId"))) {
                handAddReceiver.put("userId", handAddReceivers.get(i).getString("userId"));
                handAddReceiver.put("userName", handAddReceivers.get(i).getString("userName"));
                arrHandAddReceivers.add(handAddReceiver);
            }
        }
        //获取手动填写的抄送人
        List<JSONObject> handAddCopiers = wreportReceiverCopiersDao.getJSONListByCondition(" and sender_user_id=? and type=1", new Object[]{userId});
        for (int i = 0; i < handAddCopiers.size(); i++) {
            JSONObject handAddCopier = new JSONObject();
            if (!StringUtils.isBlank(handAddCopiers.get(i).getString("userId"))) {
                handAddCopier.put("userId", handAddCopiers.get(i).getString("userId"));
                handAddCopier.put("userName", handAddCopiers.get(i).getString("userName"));
                arrHandAddCopiers.add(handAddCopier);
            }
        }
        objResult.put("receivers", arrReceivers);
        objResult.put("copiers", arrCopiers);
        objResult.put("handAddReceivers", arrHandAddReceivers);
        objResult.put("handAddCopiers", arrHandAddCopiers);
        return objResult;
    }

    public List<JSONObject> getParentList(String userId) {
        List<JSONObject> parentList = new ArrayList<>();
        List<JSONObject> jsonParent = this.userDao.getParentList(userId, parentList);
        //判断上级
        JSONObject fistParent = this.userDao.getFirstParent(userId);
        for (int i = 0; i < jsonParent.size(); i++) {
            if (fistParent.getString("id").equals(jsonParent.get(i).getString("id"))) {
                jsonParent.remove(i);
                break;
            }
        }
        return jsonParent;
    }

    @Override
    public WReportEntity getById(String id) {
        WReportEntity wReportEntity = new WReportEntity();
        WReportMainEntity main = wReportMainDao.getById(id);

        if (main != null) {
            wReportEntity.setMain(main);
            setWReportEntity(wReportEntity);
            getLoadWReport(main.getUserId(), main.getReportDate(), wReportEntity);

        }
        return wReportEntity;

    }

    private void setWReportEntity(WReportEntity wReportEntity) {
        WReportMainEntity main = wReportEntity.getMain();
        String moduleENames=main.getModuleENames();
        String wId = main.getId();
        //心得体会
        if (moduleENames.indexOf("experience")!=-1){
            wReportEntity.setExperience(getWReportDetailByWIdAndType(wId, 1));
        }else{
            wReportEntity.setExperience(getWReportDetailByWIdAndType("", 1));
        }
        //人员情况personSituation
        if (moduleENames.indexOf("personSituation")!=-1){
            wReportEntity.setPersonSituation(getWReportDetailByWIdAndType(wId, 2));
        }else{
            wReportEntity.setPersonSituation(getWReportDetailByWIdAndType("", 2));
        }

        //第二天计划tomorrowPlan
        if (moduleENames.indexOf("tomorrowPlan")!=-1){
            wReportEntity.setTomorrowPlan(getWReportDetailByWIdAndType(wId, 3));
        }else{
            wReportEntity.setTomorrowPlan(getWReportDetailByWIdAndType("", 3));
        }

        //需要支持的事项forSupportMatters
        if (moduleENames.indexOf("forSupportMatters")!=-1){
            wReportEntity.setForSupportMatters(wReportUnfinishDao.getFinishEntityListByCondition
                    (" AND TYPE='2' AND W_ID=?", new Object[]{main.getId()}));
        }else{
            List<WReportUnfinishEntity> entityList = new ArrayList<>();
            wReportEntity.setForSupportMatters(entityList);
        }

        //当日工作情况workOnTodayDescs
        if (moduleENames.indexOf("workOnTodayDescs")!=-1){
            wReportEntity.setWorkOnTodayDescs(wReportDetailDao.getByCondition(" and W_ID = ? AND TYPE = ?", new Object[]{main.getId(), 5}));
        }else{
            List<WReportDetailEntity> entityList = new ArrayList<>();
            wReportEntity.setWorkOnTodayDescs(entityList);
        }

        //次日上午安排tomorrowAMPlan
        if (moduleENames.indexOf("tomorrowAMPlan")!=-1){
            wReportEntity.setTomorrowAMPlan(getWReportDetailByWIdAndType(wId, 6));
        }else{
            wReportEntity.setTomorrowAMPlan(getWReportDetailByWIdAndType("", 6));
        }

        //次日下午安排tomorrowPMPlan
        if (moduleENames.indexOf("tomorrowPMPlan")!=-1){
            wReportEntity.setTomorrowPMPlan(getWReportDetailByWIdAndType(wId, 7));
        }else{
            wReportEntity.setTomorrowPMPlan(getWReportDetailByWIdAndType("", 7));
        }

        //当天未处理的三个疑难故障troubleShooting
        if (moduleENames.indexOf("troubleShooting")!=-1){
            wReportEntity.setTroubleShooting(wReportUnfinishDao.getFinishEntityListByCondition
                    ("  AND TYPE = '1' AND W_ID= ?", new Object[]{main.getId()}));
        }else{
            List<WReportUnfinishEntity> entityList = new ArrayList<>();
            wReportEntity.setTroubleShooting(entityList);
        }

        //未达到拜访量的原因visitLetterReason
        if (moduleENames.indexOf("visitLetterReason")!=-1){
            wReportEntity.setVisitLetterReason(getWReportDetailByWIdAndType(wId, 9));
        }else{
            wReportEntity.setVisitLetterReason(getWReportDetailByWIdAndType("", 9));
        }

        //未关闭事项unfinishes
        if (moduleENames.indexOf("unfinishes")!=-1){
            wReportEntity.setUnfinishes(wReportUnfinishDao.getFinishEntityListByCondition
                    (" and TYPE= '3' and W_ID = ? ", new Object[]{main.getId()}));
        }else{
            List<WReportUnfinishEntity> entityList = new ArrayList<>();
            wReportEntity.setUnfinishes(entityList);
        }

        //当日拜访客户-区域经理（面访）
        // wReportEntity.setTodayCustomerVisit(wReportCusAndVisitDao.getByCondition("AND wId = ? and visitMode='1' ", new Object[]{main.getId()}));
        //当日拜访客户-区域经理（电访）
        //wReportEntity.setTodayCustomerTelVisit(wReportCusAndVisitDao.getByCondition("AND wId = ? and visitMode='0'  ", new Object[]{main.getId()}));
        //当日费用明细todayCostDetail
        //wReportEntity.setTodayCostDetail(wReportCostDao.getByCondition("AND W_ID = ? AND AUDIT_FLAG = 1 ", new Object[]{main.getId()}));
        wReportEntity.setTodayCostDetail2(wReportCostDao.getByCondition("AND W_ID = ? AND AUDIT_FLAG IS NULL ", new Object[]{main.getId()}));

        //下属当日工作描述jobDescriptionForBranch
        if (moduleENames.indexOf("jobDescriptionForBranch")!=-1){
            wReportEntity.setJobDescriptionForBranch(wReportBranchDao.getByCondition
                    (" and W_ID = ? ", new Object[]{main.getId()}));
        }else{
            List<WReportBranchEntity> entityList = new ArrayList<>();
            wReportEntity.setJobDescriptionForBranch(entityList);
        }

        //当天收款情况todayGatherSituation
        if (moduleENames.indexOf("todayGatherSituation")!=-1){
            wReportEntity.setTodayGatherSituation(wReportGatherDao.getByCondition
                    (" and W_ID = ?", new Object[]{main.getId()}));
        }else{
            List<WReportGatherEntity> entityList = new ArrayList<>();
            wReportEntity.setTodayGatherSituation(entityList);
        }

        //第二天拜访计划tomorrowVisitPlan
        if (moduleENames.indexOf("tomorrowVisitPlan")!=-1){
            wReportEntity.setTomorrowVisitPlan
                    (tomorrowVisitDao.getByCondition(" and W_ID = ?", new Object[]{main.getId()}));
        }else{
            List<TomorrowVisitPlanEntity> entityList = new ArrayList<>();
            wReportEntity.setTomorrowVisitPlan(entityList);
        }

        //当天知道丢单情况todayKnowVieSituation
        if (moduleENames.indexOf("todayKnowVieSituation")!=-1){
            WReportVieEntity wReportVieEntity = new WReportVieEntity();
            List<WReportVieEntity> wReportVieEntityList = wReportVieDao.getByCondition("and W_ID = ?", new Object[]{main.getId()});
            if (wReportVieEntityList != null && wReportVieEntityList.size() > 0) {
                wReportVieEntity = wReportVieEntityList.get(0);
            }
            wReportEntity.setTodayKnowVieSituation(wReportVieEntity);
        }else {
            WReportVieEntity wReportVieEntity = new WReportVieEntity();
            wReportEntity.setTodayKnowVieSituation(wReportVieEntity);
        }

    }

    /**
     * 写工作报告带出某些模块
     *
     * @param userId
     * @param reportDate
     * @param wReportEntity
     */
    private void getLoadWReport(String userId, String reportDate, WReportEntity wReportEntity) {
        String moduleENames="";
        if (null!=wReportEntity.getMain()){
            moduleENames=wReportEntity.getMain().getModuleENames();
        }
        JSONObject jsonObjectUser = userDao.getViewJSONById(userId);
        Integer frontFlag = null;
        Integer areaType = null;
        if (jsonObjectUser != null) {
            frontFlag = jsonObjectUser.getInteger("frontFlag");
            areaType = jsonObjectUser.getInteger("areaType");
        }
        //费用
        List<WReportCostEntity> wReportCostEntity = new ArrayList<>();
        int CostSmallId;
        String remark = "";
        StringBuffer sqlCondition = new StringBuffer();
        sqlCondition.append("\n" +
                "SELECT \n" +
                "t_wrt_cost_detail.LICENSE AS license,\n" +
                "t_wrt_cost_detail.MILEAGE AS mileage,\n" +
                "t_wrt_cost_detail.RESIDENCE AS residence,\n" +
                "t_wrt_cost_detail.HOTEL_NAME AS hotelName,\n" +
                "t_wrt_cost_detail.HOTEL_TEL AS hotelTel,\n" +
                "t_wrt_cost_detail.`HOST` AS host,\n" +
                "t_wrt_cost_detail.GUESTS AS guests,\n" +
                "t_wrt_cost_detail.PREDICT_MONEY AS prediceMoney,\n" +
                "t_wrt_cost_detail.RESTAURANT_NAME AS restaurantName,\n" +
                "t_wrt_cost_detail.BEFORE_OFFICE AS beforeOffice,\n" +
                "t_wrt_cost_detail.AFTER_OFFICE AS afterOffice\n" +

                "FROM t_wrt_cost_detail\n" +
                "WHERE 1=1");
        sqlCondition.append(" AND FK_COST_ID = ? ");
        wReportCostEntity = wReportCostDao.getByCondition("AND CREATE_USER_ID = ?  AND LEFT (REPORT_DATE, 10) = ? AND AUDIT_FLAG <> -1 AND MONEY IS NOT NULL AND IMG IS NOT NULL", new Object[]{userId, reportDate});
        for (int i = 0; i < wReportCostEntity.size(); i++) {
            if (!wReportCostEntity.get(i).getRemark().contains("备注：")) {
                remark = "备注：" + wReportCostEntity.get(i).getRemark();
                wReportCostEntity.get(i).setRemark(remark);
                CostSmallId = wReportCostEntity.get(i).getCostSmallId();
                JSONObject jsonObject = costDetailDao.queryForJsonObject(sqlCondition.toString(), new String[]{wReportCostEntity.get(i).getId()});
                if (CostSmallId == 15 || CostSmallId == 18) {
                    wReportCostEntity.get(i).setRemark("车牌号:" + jsonObject.getString("license") + ",公里数:" + jsonObject.getString("mileage") + "," + remark);

                } else if (CostSmallId == 27) {

                    wReportCostEntity.get(i).setRemark("住宿人数:" + jsonObject.getString("residence") + ",宾馆名称:" + jsonObject.getString("hotelName") + ",宾馆电话:" + jsonObject.getString("hotelTel") + "," + remark);

                } else if (CostSmallId == 40) {

                    wReportCostEntity.get(i).setRemark("招待人数:" + jsonObject.getString("guests") + ",招待对象:" + jsonObject.getString("host") + ",饭店名称:" + jsonObject.getString("restaurantName") + ",预计金额:" + jsonObject.getString("prediceMoney") + "," + remark);

                } else if (CostSmallId == 38) {
                    BigDecimal before = new BigDecimal(0.00);
                    BigDecimal after = new BigDecimal(0.00);
                    BigDecimal sub = new BigDecimal(0.00);
                    // BigDecimal bigDecimal=new BigDecimal( jsonObject.getBigDecimal("afterOffice").subtract(jsonObject.getBigDecimal("beforeOffice")).doubleValue());

                    if (!StringUtils.isBlank(jsonObject.getString("beforeOffice"))) {
                        before = jsonObject.getBigDecimal("beforeOffice");

                    }
                    if (!StringUtils.isBlank(jsonObject.getString("afterOffice"))) {
                        after = jsonObject.getBigDecimal("afterOffice");
                        sub = after.subtract(before);
                    }
                    BigDecimal bigDecimal = new BigDecimal(sub.doubleValue());
                    double doubleBigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    //double lc=bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                    wReportCostEntity.get(i).setRemark("出发前里程:" + jsonObject.getString("beforeOffice") + ",返回后里程:" + jsonObject.getString("afterOffice") + ",行驶里程:" + doubleBigDecimal + "," + remark);

                }
            } else {
                wReportCostEntity.get(i).setRemark(wReportCostEntity.get(i).getRemark());
            }
        }
        wReportEntity.setTodayCostDetail(wReportCostEntity);
        if (StringUtils.isBlank(moduleENames)) {
            //当日面访客户
            List<WReportCusAndVistEntity> todayCustomerVisit = new ArrayList<>();
            //当日电访客户
            List<WReportCusAndVistEntity> todayCustomerTelVisit = new ArrayList<>();
            //当日拜访客户大区经理
//            List<WReportCusAndVistEntity> todayVisitCustomerBigRegion = new ArrayList<>();
            //当日拜访客户区域经理
            List<WReportCusAndVistEntity> todayVisitCustomer = new ArrayList<>();
            if (frontFlag==1){

                todayCustomerVisit = wReportCusAndVisitDao.getByCondition("AND reportDate = ? AND createUserId = ?  AND visitMode=1 ", new Object[]{reportDate, userId});
                wReportEntity.setTodayCustomerVisit(todayCustomerVisit);


                todayCustomerTelVisit = wReportCusAndVisitDao.getByCondition("AND reportDate = ? AND createUserId = ?  AND visitMode=0 ", new Object[]{reportDate, userId});
                wReportEntity.setTodayCustomerTelVisit(todayCustomerTelVisit);


                todayVisitCustomer = wReportCusAndVisitDao.getByCondition("AND reportDate = ? AND createUserId = ?", new Object[]{reportDate, userId});
                wReportEntity.setTodayVisitCustomer(todayVisitCustomer);


//                todayVisitCustomerBigRegion = wReportCusAndVisitDao.getEntourage(" and t_wrt_customer_visit.ENTOURAGE_ID=? AND t_wrt_customer_visit.REPORT_DATE=?", new Object[]{userId, reportDate});
//                wReportEntity.setTodayVisitCustomerBigRegion(todayVisitCustomerBigRegion);
            }else{
                wReportEntity.setTodayCustomerVisit(todayCustomerVisit);
                wReportEntity.setTodayCustomerTelVisit(todayCustomerTelVisit);
                wReportEntity.setTodayVisitCustomer(todayVisitCustomer);
//                wReportEntity.setTodayVisitCustomerBigRegion(todayVisitCustomerBigRegion);
            }
        }else {
            //当日面访客户
            List<WReportCusAndVistEntity> todayCustomerVisit = new ArrayList<>();
           if (moduleENames.indexOf("todayCustomerVisit")!=-1){
               todayCustomerVisit = wReportCusAndVisitDao.getByCondition("AND reportDate = ? AND createUserId = ?  AND visitMode=1 ", new Object[]{reportDate, userId});
               wReportEntity.setTodayCustomerVisit(todayCustomerVisit);
           }else{
               wReportEntity.setTodayCustomerVisit(todayCustomerVisit);
           }


           //当日电访客户
            List<WReportCusAndVistEntity> todayCustomerTelVisit = new ArrayList<>();
            if (moduleENames.indexOf("todayCustomerTelVisit")!=-1) {
                todayCustomerTelVisit = wReportCusAndVisitDao.getByCondition("AND reportDate = ? AND createUserId = ?  AND visitMode=0 ", new Object[]{reportDate, userId});
                wReportEntity.setTodayCustomerTelVisit(todayCustomerTelVisit);
            }else{
                wReportEntity.setTodayCustomerTelVisit(todayCustomerTelVisit);
            }

            //当日拜访客户区域经理
            //当日拜访客户大区经理
//            List<WReportCusAndVistEntity> todayVisitCustomerBigRegion = new ArrayList<>();
            List<WReportCusAndVistEntity> todayVisitCustomer = new ArrayList<>();
            if (moduleENames.indexOf("todayVisitCustomerLetters")!=-1
                    ||moduleENames.indexOf("todayVisitCustomerDebt")!=-1
                    ||moduleENames.indexOf("todayVisitCustomerService")!=-1
                    ||moduleENames.indexOf("todayVisitCustomer")!=-1
            ) {

                    todayVisitCustomer = wReportCusAndVisitDao.getByCondition("AND reportDate = ? AND createUserId = ?", new Object[]{reportDate, userId});

                wReportEntity.setTodayVisitCustomer(todayVisitCustomer);


//                todayVisitCustomerBigRegion = wReportCusAndVisitDao.getEntourage(" and t_wrt_customer_visit.ENTOURAGE_ID=? AND t_wrt_customer_visit.REPORT_DATE=?", new Object[]{userId, reportDate});
//                wReportEntity.setTodayVisitCustomerBigRegion(todayVisitCustomerBigRegion);
            }else{
                wReportEntity.setTodayVisitCustomer(todayVisitCustomer);
//                wReportEntity.setTodayVisitCustomerBigRegion(todayVisitCustomerBigRegion);
            }

        }
    }


    private WReportDetailEntity getWReportDetailByWIdAndType(String wId, Integer type) {
        WReportDetailEntity model = new WReportDetailEntity();
        model.setType(type);
        if (!StringUtils.isBlank(wId)){
            List<WReportDetailEntity> list = wReportDetailDao.getByCondition(" and W_ID = ? AND TYPE = ?", new Object[]{wId, type});
            if (list != null && list.size() > 0) {
                model = list.get(0);
            }
        }
        return model;
    }

    @Override
    public WReportCustomerEntity getCustomerByTel(String jsonData) {
        JSONObject obj_params = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String tel = obj_params.getString("tel");
        return wReportCustomerDao.getByTel(tel);
    }

    @Override
    public List<JSONObject> getExpenseByParentId(String parentId, String userId) {
        String condition = "";
        List<JSONObject> jsonObjects = userDao.getViewJSONListByCondition(" and id=? and main=1", new Object[]{userId});


        for (int i = 0; i < jsonObjects.size(); i++) {
            if (jsonObjects.get(i).getString("parentId").equals("2017121618514C22B68296F31AF8DDE2")){
                condition = " AND expenses.PARENT_ID = ? ";//暂时还原成pc可以申请任何费用
            }else {
                if (!jsonObjects.get(i).getString("roleName").equals("总经理")
                        && !jsonObjects.get(i).getString("roleName").equals("销售总监")
                        && !jsonObjects.get(i).getString("roleName").equals("审计副总裁")
                        && !jsonObjects.get(i).getString("roleName").equals("销售后台")
                        && !jsonObjects.get(i).getString("roleName").equals("大客户总经理")
                        && !jsonObjects.get(i).getString("roleName").equals("大客户总监")
                        && !jsonObjects.get(i).getString("roleName").equals("二手机经理")
                        && !jsonObjects.get(i).getString("roleName").equals("债权总监")) {
                    condition = " AND expenses.PARENT_ID = ? AND expenses.TEMPORARY_COST!=\"0\" AND expenses.`NAME`!=\"餐费\" AND expenses.`NAME`!=\"娱乐费用\"";
                } else {
                    condition = " AND expenses.PARENT_ID = ? ";//暂时还原成pc可以申请任何费用
                }
            }
        }
        String[] params = {parentId};
        List<JSONObject> jsonObjectList = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        List<JSONObject> jsonObjects1 = this.wReportExpensesDao.getByCondition(condition, params);
        jsonObject.put("id", "");
        jsonObject.put("name", "");
        jsonObject.put("parentId", 0);
        jsonObject.put("phoneName", "");
        jsonObject.put("sortNo", "");
        jsonObject.put("temporaryCost", "");
        jsonObjectList.add(jsonObject);
        for (int i = 0; i < jsonObjects1.size(); i++) {
            jsonObjectList.add(jsonObjects1.get(i));
        }

        return jsonObjectList;
    }

    @Override
    public List<JSONObject> getCustomerType() {
        return wReportCustomerDao.getCustomerType();
    }

    @Override
    public JSONObject getReceiverAndCopiersByUserIdAndReportDate(String userId, String reportDate) {
        JSONObject objResult = new JSONObject();
        JSONArray arrReceivers = new JSONArray();
        JSONArray arrCopiers = new JSONArray();

        String dataId = "";
        String emailId = "";
        List<JSONObject> listEmail = emailDao.getJSONListByPage(" AND E_TYPE = 1 AND CREATE_USER_ID = ? ORDER BY CREATE_TIME DESC ", new Object[]{userId}, 1, 1);
        if (listEmail != null && listEmail.size() > 0) {
            dataId = listEmail.get(0).getString("dataId");
            emailId = listEmail.get(0).getString("id");

            List<JSONObject> receivers = emailReceiverDao.getJSONListByCondition(" AND EMAIL_ID = ? AND USER_TYPE = 0 AND USER_ID IN (SELECT ID FROM T_SYS_USER WHERE JOB_STATE <> 1) ", new String[]{emailId});
            List<JSONObject> copiers = emailReceiverDao.getJSONListByCondition(" AND EMAIL_ID = ? AND USER_TYPE = 1 AND USER_ID IN (SELECT ID FROM T_SYS_USER WHERE JOB_STATE <> 1) ", new String[]{emailId});
            for (int i = 0; i < receivers.size(); i++) {
                arrReceivers.add(receivers.get(i));
            }
            for (int i = 0; i < copiers.size(); i++) {
                arrCopiers.add(copiers.get(i));
            }
        } else {
            //如果没有发报告，则取直接上级，间接上级，后台支持
            JSONObject parent = userDao.getFirstParent(userId);
            if (parent != null) {
                JSONObject receiver = new JSONObject();
                receiver.put("userId", parent.getString("id"));
                receiver.put("userName", parent.getString("name"));
                arrReceivers.add(receiver);
            }
            //获取区域支持
            JSONObject support = userDao.getSupportByUserId(userId);
            if (support != null) {
                JSONObject receiver = new JSONObject();
                receiver.put("userId", support.getString("id"));
                receiver.put("userName", support.getString("name"));
                arrReceivers.add(receiver);
            }

            List<JSONObject> parents = new ArrayList<>();
            userDao.getParentList(userId, parents);

            for (int i = 0; i < parents.size(); i++) {
                if (!parents.get(i).getString("id").equals("0") && !StringUtils.isEmpty(parents.get(i).getString("id"))) {
                    if (parent != null) {
                        if (!parents.get(i).getString("id").equals(parent.getString("id"))) {
                            JSONObject copier = new JSONObject();
                            copier.put("userId", parents.get(i).getString("id"));
                            copier.put("userName", parents.get(i).getString("name"));
                            arrCopiers.add(copier);
                        }
                    } else {
                        JSONObject copier = new JSONObject();
                        copier.put("userId", parents.get(i).getString("id"));
                        copier.put("userName", parents.get(i).getString("name"));
                        arrCopiers.add(copier);
                    }
                }
            }

            UserEntity user = (UserEntity) userDao.getIBaseEntityById(userId);

            if (roleDao.frontFlagIs(user.getRoleId())) {
                List<JSONObject> supports = userDao.getSupportersByUserId(userId);
                for (int i = 0; i < supports.size(); i++) {
                    JSONObject copier = new JSONObject();
                    copier.put("userId", supports.get(i).getString("id"));
                    copier.put("userName", supports.get(i).getString("name"));
                    arrCopiers.add(copier);
                }
            }
        }
        objResult.put("receivers", arrReceivers);
        objResult.put("copiers", arrCopiers);
        return objResult;
    }


    @Override
    public List<JSONObject> getList(int year, int month, String userId) {
        UserEntity user = (UserEntity) userDao.getIBaseEntityById(userId);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//创建日期转换对象HH:mm:ss为时分秒，年月日为yyyy-MM-dd
        Date dateNow = new Date();

        List<String> listMonthDates = this.getDayListOfMonth(year, month);
        Calendar cal = Calendar.getInstance(Locale.CHINA);
        cal.set(Calendar.YEAR, year);//年设置为2015年
        cal.set(Calendar.MONTH, month - 1);//7月的id是6
        List<WReportMainEntity> listReports = wReportMainDao.getByCondition(" AND USER_ID = ? AND REPORT_DATE LIKE ? ", new String[]{userId, "%" + this.formatMonth(cal.getTime()) + "%"});

        List<JSONObject> listResult = new ArrayList<>();
        for (int i = 0; i < listMonthDates.size(); i++) {
            String day = listMonthDates.get(i);
            JSONObject obj = new JSONObject();
            obj.put("reportDate", day);
            try {
                Date dateToday = df.parse(day + " 00:00:00");

                Calendar c = Calendar.getInstance();
                c.setTime(dateToday);
                c.add(Calendar.DAY_OF_MONTH, 1);// +1天
                Date dateTomrrow = c.getTime();

                Date dateEditStart = df.parse(day + " 16:45:00");//将字符串转换为date类型
                Date draftStart = df.parse(day + " 08:30:00");//将字符串转换为date类型
                Date dateEditEnd = df.parse(this.formatDate(dateTomrrow) + " 03:00:00");
                Date dateReissueEnd = df.parse(this.formatDate(dateTomrrow) + " 12:00:00");
                obj.put("draft", dateNow.after(draftStart) && dateNow.before(dateEditEnd));
                obj.put("editable", dateNow.after(dateEditStart) && dateNow.before(dateReissueEnd));
                obj.put("dateEditStart", this.formatDateTime(dateEditStart));
                obj.put("dateEditEnd", this.formatDateTime(dateEditEnd));
                obj.put("dateReissueEnd", dateNow.after(dateEditEnd) && dateNow.before(dateReissueEnd));
                obj.put("dateBrower", dateNow.after(dateReissueEnd));
            } catch (Exception e) {
                obj.put("draft", "error");
                obj.put("editable", "error");
                obj.put("dateEditStart", "error");
                obj.put("dateEditEnd", "error");
            }
            obj.put("userId", userId);
            obj.put("userName", user.getName());
            for (int j = 0; j < listReports.size(); j++) {
                if (day.equals(listReports.get(j).getReportDate())) {
                    obj.put("id", listReports.get(j).getId());
                    obj.put("flage", listReports.get(j).getFlage());
                    obj.put("createTime", this.formatDateTime(listReports.get(j).getCreateTime()));
                    break;
                }
            }
            listResult.add(obj);
        }
        return listResult;
    }

    @Override
    public int getDayOfMonth() {
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int day = aCalendar.getActualMaximum(Calendar.DATE);
        return day;
    }

    @Override
    public List<String> getDayListOfMonth() {
        List<String> list = new ArrayList();
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int year = aCalendar.get(Calendar.YEAR);//年份
        int month = aCalendar.get(Calendar.MONTH);//月份
        int day = aCalendar.getActualMaximum(Calendar.DATE);
        for (int i = 1; i <= day; i++) {
            Calendar cal = Calendar.getInstance(Locale.CHINA);
            cal.set(Calendar.YEAR, year);//年设置为2015年
            cal.set(Calendar.MONTH, month);//7月的id是6
            cal.set(Calendar.DATE, i);
            String aDate = formatDate(cal.getTime());
            list.add(aDate);
        }
        return list;
    }

    @Override
    public int getDayOfMonth(int year, int month) {
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        aCalendar.set(Calendar.YEAR, year);//年设置为2015年
        aCalendar.set(Calendar.MONTH, month - 1);//7月的id是6
        int day = aCalendar.getActualMaximum(Calendar.DATE);//得到一个月最大的一天就是一个月多少天
        return day;
    }

    @Override
    public List<String> getDayListOfMonth(int year, int month) {
        List<String> list = new ArrayList();
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        aCalendar.set(Calendar.YEAR, year);//年设置为2015年
        aCalendar.set(Calendar.MONTH, month - 1);//7月的id是6
        int day = aCalendar.getActualMaximum(Calendar.DATE);
        for (int i = 1; i <= day; i++) {
            Calendar cal = Calendar.getInstance(Locale.CHINA);
            cal.set(Calendar.YEAR, year);//年设置为2015年
            cal.set(Calendar.MONTH, month - 1);//7月的id是6
            cal.set(Calendar.DATE, i);
            String aDate = formatDate(cal.getTime());
            list.add(aDate);
        }
        return list;
    }

    @Override
    public String formatDateTime(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date.getTime());
        return dateString;
    }

    @Override
    public String formatDate(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date.getTime());
        return dateString;
    }

    @Override
    public String formatMonth(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        String dateString = formatter.format(date.getTime());
        return dateString;
    }

    @Override
    public List<JSONObject> getDayCharge(String userId, String reportDate) {
        List<JSONObject> prerecords = wReportMainDao.getDayCharge(userId, reportDate);
        List<JSONObject> records = new ArrayList<JSONObject>();
        for (JSONObject o : prerecords) {
            if ("1".equals(o.getString("auditFlag")) && !StringUtils.isBlank(o.getString("money")) && !"".equals(o.getString("img"))) {
                List<JSONObject> costSmallNames = wReportMainDao.getByDetail(o.getString("costBigId"));
                o.put("costSmallNameList", costSmallNames);
                records.add(o);
            }
        }
        return records;
    }
}
